package com.ehualu.core.util.sms.service;

import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.xfire.client.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ehualu.core.property.PropertyConfig;
import com.ehualu.core.util.sms.pojo.Sms;
import com.ehualu.core.util.sms.pojo.SmsResponse;
import com.ehualu.core.util.sms.pojo.SmsResponseStatus;
import com.ehualu.core.util.sms.pojo.WhjgSmsResult;
import com.ehualu.msg.util.XMLUtil;


/**
 * 武汉交管短信接口
 */
public class WhjgSmsService{

	private static final Logger logger = LoggerFactory.getLogger(WhjgSmsService.class);
	/**
	 * 短信发送(武汉交管)
	 * SmsRecord phone,msg
	 * @return
	 */
	public String sendSms(Sms sms){
try {
		
		String jkid = PropertyConfig.getProperty("WUJG_SMS_JKID");//接口ID
		String sqm = PropertyConfig.getProperty("WUJG_SMS_SQM");//授权码
		String url = PropertyConfig.getProperty("WUJG_SMS_URL_NEW");//访问地址
		String user = PropertyConfig.getProperty("WUJG_SMS_USER");//用户名
		
		System.out.println("jkid="+jkid);
		System.out.println("sqm="+sqm);
		System.out.println("url="+url);
		System.out.println("user="+user);
		Client client = new Client(new URL(url));
		
		
		Map<String,Object> map  = new HashMap<String, Object>();
		map.put("user", user);
		map.put("sendType", "1");
		map.put("sendTime", "");
		map.put("phone", sms.getPhone());
		map.put("smsContext", sms.getMessage());
		map.put("operator", "");
		
		String xmlDoc = XMLUtil.createXmlParam(map);
		logger.info("-----------------XML---------------------"+xmlDoc);
		String message = XMLUtil.encodeUTF8(xmlDoc);
		logger.info("-----------------输入参数---------------------"+message);
		Object[] result = client.invoke("write", new Object[]{jkid,sqm,message});
		
		logger.info("-----------------返回结果---------------------");
		// 打印响应状态
		logger.info(result[0].toString());
		WhjgSmsResult ws = XMLUtil.parseXml(result[0].toString());
		if (ws != null) {
			//判断返回数据中是否包含status
			if(("1").equals(ws.getCode())){
					return JSON.toJSONString(new SmsResponse(SmsResponseStatus.SUCCESS.getStatus(),SmsResponseStatus.SUCCESS.getCode(),SmsResponseStatus.SUCCESS.getReason()));
			}else{
				return JSON.toJSONString(new SmsResponse(SmsResponseStatus.FAIL.getStatus(),SmsResponseStatus.FAIL.getCode(),ws.getMessage()));
			}
		}else{
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.RESULT_IS_NULL.getStatus(),SmsResponseStatus.RESULT_IS_NULL.getCode(),SmsResponseStatus.RESULT_IS_NULL.getReason()));
		}
		} catch (ClientProtocolException e) {
			logger.info("httpclient  is exception : ");
			e.printStackTrace();
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.REQUEST_ERROR.getStatus(),SmsResponseStatus.REQUEST_ERROR.getCode(),SmsResponseStatus.REQUEST_ERROR.getReason()));
		} catch (IOException e) {
			logger.info("whjg send sms  is exception : ");
			e.printStackTrace();
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.SYSTEM_IS_EXCEPTION.getStatus(),SmsResponseStatus.SYSTEM_IS_EXCEPTION.getCode(),SmsResponseStatus.SYSTEM_IS_EXCEPTION.getReason()));
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.SYSTEM_IS_EXCEPTION.getStatus(),SmsResponseStatus.SYSTEM_IS_EXCEPTION.getCode(),SmsResponseStatus.SYSTEM_IS_EXCEPTION.getReason()));
		}
	}
	
	@SuppressWarnings("unused")
	private String sendOne(Sms sms){
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			
			HttpPost httppost = new HttpPost(PropertyConfig.getProperty("WUJG_SMS_URL"));
			
			List<NameValuePair> nvps = generateRequestBody(sms);
	        httppost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
			logger.info("执行短信发送: " + httppost.getURI());
			//System.out.println("执行短信发送: " + httppost.getURI());
			// 执行post请求.
			CloseableHttpResponse response = httpclient.execute(httppost);
			// 获取响应实体
			HttpEntity entity = response.getEntity();
			logger.info("--------------------------------------");
			//System.out.println("--------------------------------------");
			// 打印响应状态
			logger.info(response.getStatusLine().toString());
			System.out.println(response.getStatusLine().toString());
			String entityString = null;
			if (entity != null) {
				// 打印响应内容长度
				logger.info("响应内容长度: " + entity.getContentLength());
				//System.out.println("响应内容长度: " + entity.getContentLength());
				entityString = EntityUtils.toString(entity,"UTF-8");
				// 打印响应内容
				logger.info("响应内容: " + entityString);
				System.out.println("响应内容: " + entityString);
				//判断返回数据中是否包含status
				if(JSON.parseObject(entityString).containsKey("status")){
					//判断status的状态
					if(("ok").equals(JSON.parseObject(entityString).get("status"))){
						return JSON.toJSONString(new SmsResponse(SmsResponseStatus.SUCCESS.getStatus(),SmsResponseStatus.SUCCESS.getCode(),SmsResponseStatus.SUCCESS.getReason()));
						
						//短信发送失败	
					}else if(("error").equals(JSON.parseObject(entityString).get("status"))){
						String msg = JSON.parseObject(entityString).get("msg").toString();
						return JSON.toJSONString(new SmsResponse(SmsResponseStatus.FAIL.getStatus(),SmsResponseStatus.FAIL.getCode(),msg==null ? SmsResponseStatus.FAIL.getReason() : msg));
						
						//返回结果的结构体错误
					}else{
						return JSON.toJSONString(new SmsResponse(SmsResponseStatus.RESULT_IS_ERROR.getStatus(),SmsResponseStatus.RESULT_IS_ERROR.getCode(),SmsResponseStatus.RESULT_IS_ERROR.getReason()));
					}
				}else{
					return JSON.toJSONString(new SmsResponse(SmsResponseStatus.SUCCESS.getStatus(),SmsResponseStatus.SUCCESS.getCode(),SmsResponseStatus.SUCCESS.getReason()));
				}
			}else{
				return JSON.toJSONString(new SmsResponse(SmsResponseStatus.RESULT_IS_NULL.getStatus(),SmsResponseStatus.RESULT_IS_NULL.getCode(),SmsResponseStatus.RESULT_IS_NULL.getReason()));
			}
		} catch (ClientProtocolException e) {
			logger.info("httpclient  is exception : ");
			e.printStackTrace();
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.REQUEST_ERROR.getStatus(),SmsResponseStatus.REQUEST_ERROR.getCode(),SmsResponseStatus.REQUEST_ERROR.getReason()));
		} catch (IOException e) {
			logger.info("whjg send sms  is exception : ");
			e.printStackTrace();
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.SYSTEM_IS_EXCEPTION.getStatus(),SmsResponseStatus.SYSTEM_IS_EXCEPTION.getCode(),SmsResponseStatus.SYSTEM_IS_EXCEPTION.getReason()));
		}finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
				return JSON.toJSONString(new SmsResponse(SmsResponseStatus.CLOSE_HTTPCLIENT_FAIL.getStatus(),SmsResponseStatus.CLOSE_HTTPCLIENT_FAIL.getCode(),SmsResponseStatus.CLOSE_HTTPCLIENT_FAIL.getReason()));
			}
		}
	}
	
	private static List<NameValuePair> generateRequestBody(Sms sms){
		
        long timestamp = System.currentTimeMillis();
        
        //公钥
		String publickey = PropertyConfig.getProperty("WUJG_PUBLIC_KEY");
		
		//私钥
		String privatekey = PropertyConfig.getProperty("WUJG_PRIVATE_KEY");
        
		//短信发送类型
		String requesttype = PropertyConfig.getProperty("WUJG_REQ_TYPE");
		
        String pwd = timestamp + publickey + privatekey;
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] bytes = md.digest(pwd.getBytes());
        StringBuffer sb = new StringBuffer();
        String token = "";
        for (int i = 0; i < bytes.length; i++){
            int j = bytes[i] & 0xff;
            if (j < 16) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(j));
        }
        token = sb.toString();
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();
        
        nvps.add(new BasicNameValuePair("timestamp", String.valueOf(timestamp)));  
        nvps.add(new BasicNameValuePair("publickey", publickey));
        
        nvps.add(new BasicNameValuePair("accesstoken", token));
        nvps.add(new BasicNameValuePair("requesttype", requesttype));
        nvps.add(new BasicNameValuePair("requestbody", JSON.toJSONString(sms)));
        nvps.add(new BasicNameValuePair("serviceno", String.valueOf(timestamp)));
        
        System.out.println("param="+nvps.toString());
        return nvps;
    }
	public static void main(String[] args) {
		WhjgSmsService ws = new WhjgSmsService();
		Sms sms = new Sms();
		sms.setMessage("收到消息，在微信上回复一下");
		sms.setPhone("15827520616");
		ws.sendSms(sms);
	}
}
